from fastapi import Request, status
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from sqlalchemy.exc import SQLAlchemyError
from typing import Union

from schemas.Result import Result

async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """
    请求参数验证异常处理
    """
    # 提取错误详情
    error_details = exc.errors()
    error_messages = []
    
    for error in error_details:
        # 获取错误位置
        loc = " -> ".join(str(loc_item) for loc_item in error["loc"])
        # 获取错误消息
        msg = error["msg"]
        # 组合错误信息
        error_messages.append(f"{loc}: {msg}")
    
    # 组合所有错误信息
    error_msg = "请求参数错误: " + "; ".join(error_messages)
    
    # 返回统一格式的错误响应
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content=Result.fail(msg=error_msg, code=400).dict()
    )

async def sqlalchemy_exception_handler(request: Request, exc: SQLAlchemyError):
    """
    数据库异常处理
    """
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content=Result.fail(msg=f"数据库错误: {str(exc)}", code=500).dict()
    )

async def http_exception_handler(request: Request, exc: Exception):
    """
    通用异常处理
    """
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content=Result.fail(msg=f"服务器内部错误: {str(exc)}", code=500).dict()
    )